package com.sdx.console.live.web;

import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.ibeetl.admin.core.annotation.Function;
import com.ibeetl.admin.core.entity.BaseEntity;
import com.ibeetl.admin.core.entity.CoreOrg;
import com.ibeetl.admin.core.entity.CoreUser;
import com.ibeetl.admin.core.service.CorePlatformService;
import com.ibeetl.admin.core.util.DateUtil;
import com.ibeetl.admin.core.util.ValidateConfig;
import com.ibeetl.admin.core.web.AuthorizedBaesController;
import com.ibeetl.admin.core.web.JsonResult;
import com.ibeetl.admin.core.web.JsonReturnCode;
import com.sdx.common.entity.ResCloudFile;
import com.sdx.common.service.ResCloudFileService;
import com.sdx.common.utils.FileUtils;
import com.sdx.common.utils.JacksonUtils;
import com.sdx.common.utils.Utils;
import com.ibeetl.admin.core.service.RedisService;
import com.sdx.console.common.service.BaseDataService;
import com.sdx.console.content.service.ResContentMainService;
import com.sdx.console.customer.entity.CustomerInfo;
import com.sdx.console.customer.service.CustomerInfoService;
import com.sdx.console.live.entity.CourseLive;
import com.sdx.console.live.service.CourseLiveService;
import com.sdx.console.person.service.CustomerExtInfoService;
import com.sdx.service.ConfigService;
import com.sdx.third.AliOSSApi;
import org.beetl.sql.core.engine.PageQuery;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;


/**
 * 直播 接口
 */
@RequestMapping("/live/courseLive")
@Controller
public class CourseLiveController extends AuthorizedBaesController{
	private static final Logger log = LoggerFactory.getLogger(CourseLiveController.class);
    private static final String MODEL = "/live/courseLive";


    @Resource
	private CourseLiveService courseLiveService;

    @Resource
    private BaseDataService baseDataService;

    @Resource
    private CorePlatformService platformService;

    @Resource
    private CustomerExtInfoService customerExtInfoService;

    @Resource
    private CorePlatformService corePlatformService;

    @Resource
    private ResContentMainService resContentMainService;

    @Resource
    private ResCloudFileService resCloudFileService;

    @Resource
    private CustomerInfoService customerInfoService;

    @Resource
    private RedisService redisService;

	/**
	 * 初始化页面需要的列表数据，
	 *
	 */
	private void setPageParam(ModelAndView view,HttpServletRequest request) {
        Integer accessType = platformService.getAccessType(request);
        view.addObject("accessType",accessType);
        Integer provinceId = null;
        if(accessType<6){
            CoreOrg currentOrg = corePlatformService.getCurrentOrg();
            provinceId = currentOrg.getProvinceId();
        }
        view.addObject("provinceId",provinceId);
        view.addObject("provinceList",baseDataService.getAllProvince());

	}

    @RequestMapping("/entrance.do")
    @Function("live.courseLive.entrance")
    @ResponseBody
    public ModelAndView entrancePage(HttpServletRequest request) {
        ModelAndView view = new ModelAndView(MODEL+"/entrance.html") ;
        return view;
    }

    @PostMapping("/entrance.json")
    @ResponseBody
    public JsonResult entrance(boolean flag) {
	    String key = "LIVE_ENTRSNCE_";
	    List<Object> list = new ArrayList<>();

        String platform = "";
        String url = "";
	    if(flag){
	        //圣达信H5
            JSONObject jsonSDX = new JSONObject();
             platform = key+"SDX";
             url = redisService.getValue(platform,false);
            jsonSDX.put("platform",platform);
            jsonSDX.put("name","圣达信H5");
            jsonSDX.put("url",url);
            list.add(jsonSDX);
            //高三网
            JSONObject jsonGSW = new JSONObject();
            platform = key+"GSW";
            url = redisService.getValue(platform,false);
            jsonGSW.put("platform",platform);
            jsonGSW.put("name","高三网H5");
            jsonGSW.put("url",url);
            list.add(jsonGSW);
            //大学有多远
            JSONObject jsonDXYDY = new JSONObject();
            platform = key+"DXYDY";
            url = redisService.getValue(platform,false);
            jsonDXYDY.put("platform",platform);
            jsonDXYDY.put("name","大学有多远");
            jsonDXYDY.put("url",url);
            list.add(jsonDXYDY);
        }else{
            //高三网
            JSONObject jsonQT = new JSONObject();
            platform = key+"QT";
            url = redisService.getValue(platform,false);
            jsonQT.put("platform",platform);
            jsonQT.put("name","七天网络");
            jsonQT.put("url",url);
            list.add(jsonQT);
            //大学有多远
            JSONObject jsonQTH5 = new JSONObject();
            platform = key+"QTH5";
            url = redisService.getValue(platform,false);
            jsonQTH5.put("platform",platform);
            jsonQTH5.put("name","七天网络H5");
            jsonQTH5.put("url",url);
            list.add(jsonQTH5);
        }
	    return JsonResult.success(list);
    }


    @PostMapping("/updateurl.json")
    @ResponseBody
    public JsonResult entrance(String url,String platform) {
        redisService.setValue(platform,url);
        return JsonResult.success();
    }

    /* 页面 */

    @GetMapping("/index.do")
    @Function("live.courseLive.query")
    public ModelAndView index(HttpServletRequest request) {
        ModelAndView view = new ModelAndView(MODEL+"/index.html") ;
		setPageParam(view,request);
        return view;
    }

    @GetMapping("/edit.do")
    @Function("live.courseLive.edit")
    @ResponseBody
    public ModelAndView edit(HttpServletRequest request,Integer liveId) {
        ModelAndView view = new ModelAndView(MODEL+"/add.html");
        CourseLive courseLive = courseLiveService.queryById(liveId);
        view.addObject("courseLive", courseLive);
		setPageParam(view,request);
		try {
			view.addObject("courseLiveJson", JacksonUtils.toJsonString(courseLive,JacksonUtils.DF1));
		} catch (JsonProcessingException e) {
			e.printStackTrace();
		}
        return view;
    }

    @GetMapping("/add.do")
    @Function("live.courseLive.add")
    @ResponseBody
    public ModelAndView add(HttpServletRequest request) {
        ModelAndView view = new ModelAndView(MODEL+"/add.html");
        view.addObject("courseLive",new CourseLive());
		setPageParam(view,request);
        return view;
    }

    /* ajax json */

    @PostMapping("/list.json")
    @Function("live.courseLive.query")
    @ResponseBody
    public JsonResult<PageQuery> list(HttpServletRequest request,CourseLive condtion)
    {
        PageQuery page = condtion.getPageQuery();
        Integer accessType = platformService.getAccessType(request);
        if(accessType!=6){
            CoreOrg currentOrg = corePlatformService.getCurrentOrg();
            condtion.setProvinceId(currentOrg.getProvinceId());
        }
        courseLiveService.queryByCondition(page);
        return JsonResult.success(page);
    }

    private JsonResult save(boolean isNew,CourseLive courseLive,HttpServletRequest request,MultipartFile coverFile,MultipartFile coursewareUrlFile
	) {
    	JsonResult result = JsonResult.success();
		String dir = DateUtil.now("yyyyMMdd");
    	String subPath = "/images/live/"+dir+"/";
		String bucketName = "sdxcomm";
		CoreUser user = getLoginUser(request);
        if (!FileUtils.isEmptyFile(coverFile)) {
            try
            {
                String mainImgFileNamePair = FileUtils.upload(subPath,coverFile);
                String mainImgStoreFile = mainImgFileNamePair.split("::")[0];
                mainImgStoreFile = subPath+mainImgStoreFile;
                AliOSSApi.uploadLocalFile(FileUtils.getRoot()+mainImgStoreFile,bucketName,mainImgStoreFile.substring(1));
                String mainImgUrl = "https://sdxcomm."+ ConfigService.ossDomain+mainImgStoreFile;
                courseLive.setCover(mainImgUrl);
                resCloudFileService.insertResFile(ResCloudFile.ALI,mainImgStoreFile,mainImgUrl,"a","直播封面");
            }catch(Exception e) {
                e.printStackTrace();
                result.setCode(JsonReturnCode.IO_ERROR.getCode());
                result.setMsg(e.getMessage());
            }
        }


        if (!FileUtils.isEmptyFile(coursewareUrlFile)) {
            try
            {
                String mainImgFileNamePair = FileUtils.upload(subPath,coursewareUrlFile);
                String mainImgStoreFile = mainImgFileNamePair.split("::")[0];
                mainImgStoreFile = subPath+mainImgStoreFile;
                AliOSSApi.uploadLocalFile(FileUtils.getRoot()+mainImgStoreFile,bucketName,mainImgStoreFile.substring(1));
                String mainImgUrl = "https://sdxcomm."+ ConfigService.ossDomain+mainImgStoreFile;
                courseLive.setCoursewareUrl(mainImgUrl);
                resCloudFileService.insertResFile(ResCloudFile.ALI,mainImgStoreFile,mainImgUrl,"a","课件");
            }catch(Exception e) {
                e.printStackTrace();
                result.setCode(JsonReturnCode.IO_ERROR.getCode());
                result.setMsg(e.getMessage());
            }
        }
        if(courseLive.getTeacherId()!=null||courseLive.getTeacherId()!=""){
            CustomerInfo customerInfo = customerInfoService.queryById(courseLive.getTeacherId());
            if(customerInfo!=null){
                courseLive.setTearchName(customerInfo.getCustomerName());
            }
        }

    	if (isNew) {
            Integer accessType = platformService.getAccessType(request);
            if(accessType!=6){
                CoreOrg currentOrg = corePlatformService.getCurrentOrg();
                courseLive.setProvinceId(currentOrg.getProvinceId());
            }
			courseLive.setCreatedBy(user.getId().intValue());
			courseLive.setCreatedName(user.getName());
			courseLive.setCreatedTime(new Date());
			courseLive.setUpdatedBy(user.getId().intValue());
			courseLive.setUpdatedName(user.getName());
			courseLive.setUpdatedTime(new Date());
			courseLiveService.save(courseLive);
		} else {
			courseLive.setUpdatedBy(user.getId().intValue());
			courseLive.setUpdatedName(user.getName());
			courseLive.setUpdatedTime(new Date());
			courseLiveService.updateTemplate(courseLive);
		}
		return result;
	}
    @PostMapping("/add.json")
    @Function("live.courseLive.add")
    @ResponseBody
    public JsonResult add(@Validated(ValidateConfig.ADD.class)CourseLive courseLive,HttpServletRequest request
                          ,@RequestParam("coverFile") MultipartFile coverFile
                          ,@RequestParam("coursewareUrlFile") MultipartFile coursewareUrlFile
		)
    {

        return save(true,courseLive,request,coverFile,coursewareUrlFile);
    }

    @PostMapping("/update.json")
    @Function("live.courseLive.edit")
    @ResponseBody
    public JsonResult<String> update(@Validated(ValidateConfig.UPDATE.class) CourseLive courseLive,HttpServletRequest request
            ,@RequestParam("coverFile") MultipartFile coverFile
            ,@RequestParam("coursewareUrlFile") MultipartFile coursewareUrlFile
		) {
		return save(false,courseLive,request,coverFile,coursewareUrlFile	);
    }



    @GetMapping("/view.json")
    @Function("live.courseLive.query")
    @ResponseBody
    public JsonResult<CourseLive>queryInfo(Integer liveId) {
        CourseLive courseLive = courseLiveService.queryById( liveId);
        return  JsonResult.success(courseLive);
    }

    @PostMapping("/delete.json")
    @Function("live.courseLive.del")
    @ResponseBody
    public JsonResult delete(String ids) {
		List<String> idList = Utils.strToList(ids,",");
        courseLiveService.batchDelCourseLive(idList);
        return JsonResult.success();
    }


    @PostMapping("/getTeacher.json")
    @ResponseBody
    public List<BaseEntity> getTeacher(Integer provinceId) {
        List<BaseEntity> list = new ArrayList<>();
        if(provinceId!=null && provinceId ==0){
            provinceId = null;
        }
        list = resContentMainService.selectAuthor(provinceId);
        return list;
    }

    @PostMapping("/getLecture.json")
    @ResponseBody
    public List<BaseEntity> getLecture(String teacherId) {
        List<BaseEntity> list = new ArrayList<>();
        list = courseLiveService.getLecture(teacherId);
        return list;
    }


    @PostMapping("/online.json")
    @Function("live.courseLive.up")
    @ResponseBody
    public JsonResult<String> online(CourseLive courseLive,HttpServletRequest request) {
        courseLive.setCourseStatus("1");
        return saveCourseStatus(courseLive,request);
    }

    @PostMapping("/offline.json")
    @Function("live.courseLive.down")
    @ResponseBody
    public JsonResult<String> offline( CourseLive courseLive,HttpServletRequest request) {
        courseLive.setCourseStatus("0");
        return saveCourseStatus(courseLive,request);
    }
    private JsonResult saveCourseStatus(CourseLive courseLive,HttpServletRequest request) {
        JsonResult result = JsonResult.success();
        CoreUser user = getLoginUser(request);
        courseLive.setUpdatedBy(user.getId().intValue());
        courseLive.setUpdatedName(user.getName());
        courseLive.setUpdatedTime(new Date());
        courseLiveService.updateTemplate(courseLive);
        return result;
    }




}
